﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;

namespace com.citizensoft.MessageExchange
{
    internal class Context
    {
        public byte[] Buffer { get; set; }
        public TcpClient Client { get; set; }
        public Stream Stream { get; set; }

        private List<byte> _cache = new List<byte>();

        public Context(TcpClient client,Stream stream)
        {
            Buffer = new byte[4096];
            Stream = stream;
            Client = client;
        }

        public Message ExtractMessage()
        {
            if (_cache.Count > 16)
            {
                int len = BitConverter.ToInt32(_cache.Take(4).ToArray(), 0);
                if (_cache.Count >= len + 4)
                {
                    byte[] data = _cache.Take(len + 4).ToArray();
                    _cache.RemoveRange(0, len + 4);
                    return Message.FromByte(data);
                }
            }
            return null;
        }

        public void AcceptBuffer(int count)
        {
            if (count != 0)
            {
                if (count == Buffer.Length)
                {
                    _cache.AddRange(Buffer);
                }
                else
                {
                    byte[] temp = new byte[count];
                    Array.Copy(Buffer, temp, count);
                    _cache.AddRange(temp);
                }
            }
        }
    }
}
